// store/theme.ts
import { defineStore } from 'pinia';

// 定义主题类型
type ThemeMode = 'default' | 'red';

interface ThemeState {
  mode: ThemeMode;
  colors: {
    primary: string;
    background: string;
    selectedColor: string;
    text: string;
    tabBarBackground: string;
  };
}

export const useThemeStore = defineStore(
  'theme',
  () => {
    // 定义状态
    const mode = ref<ThemeMode>('default');
    const colors = reactive({
      primary: '#11E69E', // 默认主题色
      selectedColor: '#11E69E',
      background: '#F0F3F5',
      text: '#333333',
      tabBarBackground: '#f8f8f8',
    });

    // 切换主题
    function toggleTheme(data: ThemeMode) {
      mode.value = data;
      updateThemeColors();
      applyTheme();
    }

    // 更新颜色值（可扩展多套主题）
    function updateThemeColors() {
      if (mode.value === 'default') {
        Object.assign(colors, {
          primary: '#11E69E',
          selectedColor: '#11E69E',
          background: '#F0F3F5',
          text: '#333333',
          tabBarBackground: '#f8f8f8',
        });
      } else {
        Object.assign(colors, {
          primary: 'red',
          selectedColor: 'red',
          background: '#F0F3F5',
          text: '#333333',
          tabBarBackground: '#f8f8f8',
        });
      }
    }

    // 应用主题到页面和组件
    function applyTheme() {
      uni.setTabBarStyle({
        backgroundColor: colors.tabBarBackground,
        selectedColor: colors.primary
      });

      // 更新 CSS 变量
      const root = document.documentElement;
      root.style.setProperty('--u-primary-color', colors.primary);
      root.style.setProperty('--background-color', colors.background);
    }

    return { mode, colors, toggleTheme, updateThemeColors, applyTheme };
  },
  {
    persist: {
      // 显式声明类型
      // key: 'theme', // 设置存储的 key
      // paths: ['mode', 'colors'], // 持久化指定的状态路径
      storage: {
        getItem(key: string) {
          return uni.getStorageSync(key);
        },
        setItem(key: string, value: any) {
          uni.setStorageSync(key, value);
        },
      },
    },
  }
);